package com.demo.myvideoplayer;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.media.FaceDetector;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.demo.myvideoplayer.view.face.FaceDetectTextureView;
import com.demo.myvideoplayer.view.face.FaceDetectView;

import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class FaceActivity extends Activity {
    FaceDetectView faceDetectView;
    FrameLayout fl_bg;

    TextView tv_date;
    TextView tv_time;
    TextView tv_ip;

    LinearLayout ll_loading;

    LinearLayout ll_success;
    LinearLayout ll_fail;
    ImageView head;

    //语音播报
    TextToSpeech textToSpeech;
    //是否播放语音
    boolean isPlayVoice = false;
    //是否显示ip
    boolean isShowIP = false;

    Button btn_refresh;

    //每两次会识别失败一次
    int times = 0;
    //是否刚验证过
    boolean watch = false;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_face);
        faceDetectView = findViewById(R.id.faceDetectView);
        fl_bg = findViewById(R.id.fl_bg);
        tv_date = findViewById(R.id.tv_date);
        tv_time = findViewById(R.id.tv_time);
        tv_ip = findViewById(R.id.tv_ip);
        ll_success = findViewById(R.id.ll_success);
        ll_fail = findViewById(R.id.ll_fail);
        head = findViewById(R.id.head_img);
        ll_loading = findViewById(R.id.ll_loading);
        btn_refresh = findViewById(R.id.btn_refresh);

        //初始化语音播报
        textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if(status == TextToSpeech.SUCCESS){
                    int result = textToSpeech.setLanguage(Locale.CHINA);
                    if(result == TextToSpeech.LANG_NOT_SUPPORTED || result == TextToSpeech.LANG_MISSING_DATA){
                        Toast.makeText(FaceActivity.this, "该手机缺少语音包", Toast.LENGTH_SHORT).show();
                    }
                }else {
                    Toast.makeText(FaceActivity.this, "语音包初始化失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn_refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ll_loading.setVisibility(View.VISIBLE);
                getData();
            }
        });

        //获取系统时间
        Date date = new Date();
        SimpleDateFormat dateFormatDate = new SimpleDateFormat("yyyy年MM月dd日");
        SimpleDateFormat dateFormatTime = new SimpleDateFormat("hh:mm");
        tv_date.setText(dateFormatDate.format(date));
        tv_time.setText(dateFormatTime.format(date));
        faceDetectView.setFramePreViewListener(new FaceDetectTextureView.IFramePreViewListener() {
            @Override
            public boolean onFrame(Bitmap preFrame) {
                //System.out.println("111111初始化");
                return false;
            }

            @Override
            public boolean onFaceFrame(Bitmap preFrame, FaceDetector.Face[] faces) {
                //System.out.println("111111人脸个数"+faces.length);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(faces.length > 0){
                            if(watch)
                                return;
                            watch = true;
                            faceDetectView.getDetectConfig().MinDetectTime = 2000;
                            times++;
                            if(times % 3 == 0){
                                ll_success.setVisibility(View.GONE);
                                ll_fail.setVisibility(View.VISIBLE);
                                if(isPlayVoice){
                                    textToSpeech.speak("验证失败请联系管理员！", TextToSpeech.QUEUE_FLUSH, null);
                                }
                            }else {
                                head.setImageBitmap(preFrame);
                                ll_success.setVisibility(View.VISIBLE);
                                ll_fail.setVisibility(View.GONE);
                                if(isPlayVoice){
                                    textToSpeech.speak("识别成功，请通行！", TextToSpeech.QUEUE_FLUSH, null);
                                }
                            }
                            fl_bg.setVisibility(View.GONE);
                        }else {
                            watch = false;
                            faceDetectView.getDetectConfig().MinDetectTime = 500;
                            ll_success.setVisibility(View.GONE);
                            ll_fail.setVisibility(View.GONE);
                            fl_bg.setVisibility(View.VISIBLE);
                        }
                    }
                });
                return true;
            }
        });

        getData();
    }

    private void getData(){
        OkHttpClient okHttpClient = new OkHttpClient();

        Request.Builder builder=new Request.Builder();
        final Request request = builder
                .get()
                .url(LoginActivity.ip+"/conf/get?token="+LoginActivity.token+"&type=voice")
                .build();

        Call call = okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ll_loading.setVisibility(View.GONE);
                    }
                });
                String string = response.body().string();
                try {
                    JSONObject result = new JSONObject(string);
                    if(result.getBoolean("successful")){
                        JSONObject jsonValue = new JSONObject(result.getJSONObject("data").getString("value"));
                        isPlayVoice = jsonValue.has("1");
                        isShowIP = jsonValue.has("2");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if(isShowIP){
                                    tv_ip.setVisibility(View.VISIBLE);
                                    tv_ip.setText("IP:"+LoginActivity.ip);
                                }else {
                                    tv_ip.setVisibility(View.GONE);
                                }
                            }
                        });

                    }else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Toast.makeText(FaceActivity.this, result.getString("message"), Toast.LENGTH_SHORT).show();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                ll_loading.setVisibility(View.GONE);
                Toast.makeText(FaceActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
            }
        });
    }


    private static final int REQUEST_CAMERA_PERMISSION = 1;
    @Override
    protected void onResume() {
        super.onResume();
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
            faceDetectView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (!faceDetectView.isHasInit()) {
                        //必须是在view可见后进行初始化
                        faceDetectView.initView();
                        faceDetectView.initCamera();
                        faceDetectView.getDetectConfig().CameraType = Camera.CameraInfo.CAMERA_FACING_FRONT;
                        faceDetectView.getDetectConfig().EnableFaceDetect = true;
                        faceDetectView.getDetectConfig().MinDetectTime = 500;
                        faceDetectView.getDetectConfig().Simple = 0.2f;//图片检测时的压缩取样率，0~1，越小检测越流畅
                        faceDetectView.getDetectConfig().MaxDetectTime =2000;//进入智能休眠检测，以2秒一次的这个速度检测
                        faceDetectView.getDetectConfig().EnableIdleSleepOption=true;//启用智能休眠检测机制
                        faceDetectView.getDetectConfig().IdleSleepOptionJudgeTime=1000*10;//1分钟内没有检测到人脸，进入智能休眠检测
                    }
                    faceDetectView.startCameraPreview();
                }
            },1000);
        } else if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
        }

    }

}
